<template>
  <Dialog title="常用语" v-model="dialogVisible" width="500">
    <el-button type="primary" @click="setCommonTable('add')">新增</el-button>
    <el-table :data="commonPhrases">
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="content" label="内容" show-overflow-tooltip />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" link @click="setCommonTable('update', scope.row)"
            >编辑</el-button
          >
          <el-divider direction="vertical" />
          <el-button type="primary" link style="color: #ff4d4f" @click="removeField(scope.row)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </Dialog>
  <Dialog title="新增" v-model="dialog" width="500">
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" type="number" placeholder="请输入排序(值越大显示越靠前)" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="form.content" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item>
        <el-button @click="dialog = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import {
  createCommonphrase,
  updateCommonphrase,
  deleteCommonphrase
} from '@/api/service/workbench/index'
const dialogVisible = ref(false)
const dialog = ref(false)
const ruleFormRef = ref(null)
const commonType = ref('')
const tableData = ref([])
const form = ref({
  sort: '',
  content: ''
})
const rules = reactive({
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
})
const props = defineProps({
  commonPhrases: Array
})
const emit = defineEmits(['getlist'])
const open = (val) => {
  dialogVisible.value = true
}
const setCommonTable = (type, value) => {
  commonType.value = type
  if (type == 'add') {
    form.value = {
      sort: '',
      content: ''
    }
  } else {
    form.value = { ...value }
  }
  dialog.value = true
}
// 创建、编辑
const submit = async () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (commonType.value == 'add') {
        const res = await createCommonphrase({ ...form.value })
        ElMessage.success('添加成功')
        emit('getlist')
      } else {
        const res = await updateCommonphrase({ ...form.value })
        ElMessage.success('编辑成功')
        emit('getlist')
      }
      dialog.value = false
    }
  })
}
const removeField = async (value) => {
  const res = await deleteCommonphrase(value.id)
  ElMessage.success('删除成功')
  emit('getlist')
}
defineExpose({ open })
</script>

<style lang="scss" scoped></style>
